 <!-- 测试使用 <TreeSelect :multiple="true" ret-attr="value" :treeData="treeData" placeholder='Please select' strategy="SHOW_ALL" ></TreeSelect>   -->
<!--
	multiple:是否多选
	strategy：[SHOW_ALL,SHOW_CHILD] 结果返回模式 SHOW_CHILD 只返回子集 multiple=true 并且 SHOW_CHILD 模式 将出现 checkbox
	ret-attr:结果返回的字段属性 如果不设置 返回整个对象不含children属性
	支持 v-model
-->
<template>
<Dropdown class="selectree" v-clickoutside="setIsOpen.bind(this,false)" trigger="custom" :visible="isDropdown">
	<div class="selectInput" :class="{multiple:multiple}" @click="setIsOpen(true)">

		<template v-for="(item,index) in selectItems">
        		<template v-if="multiple">	        		        			        			
        			<div class="ivu-tag" >	
	                    <span class="ivu-tag-text">{{ item.title }}</span>
	                    <!-- <Icon type="ios-close-empty" @click.native.stop="removeItem(item)"></Icon> -->
	                </div>
                </template>
                <template v-else>
                     <div class="ivu-tag">
	                     <span class="ivu-tag-text">{{ item.title }}</span>
                     </div>
                </template>
        </template>  
        	<div v-show="showholder" class="tip">{{placeholder}}</div> 
        	<div v-show="!showholder && allowClear" class='tipclose' @click.stop="clearAllSelect"><Icon type="close-circled" size='16'></Icon></div>
        </div>
		<Dropdown-menu slot="list" style="padding-left:10px;max-height:300px;overflow: auto;">
           <Tree ref="reftree" :data="treeData" :multiple="multiple" :show-checkbox="showCheckbox" @on-check-change="onCheckChange" @on-select-change="onSelectChange"></Tree>
	    </Dropdown-menu>	        
       
    </Dropdown>
	
</template>


<script>
import clickoutside from "../directives/clickoutside.js";
import { setTimeout } from "timers";
export default {
  name: "tree-select",
  model: {
    // 使用model， 这儿2个属性，prop属性说，我要将msg作为该组件被使用时（此处为aa组件被父组件调用）v-model能取到的值，event说，我emit ‘cc’ 的时候，参数的值就是父组件v-model收到的值。
    prop: "value",
    event: "updateVal"
  },
  props: {
    multiple: {
      //是否多选
      type: Boolean,
      default: false
    },
    placeholder: String,
    allowClear: {
        type:Boolean,
		default:true
	},
    treeData: {
      type: Array,
      required: true
    },
    strategy: {
      //数据返回模式 SHOW_ALL:包括父级和子集 SHOW_PARENT：全选子集的时候只返回父级 SHOW_CHILD：只返回子集
      type: String,
      default: "SHOW_ALL"
    },
    retAttr: {
      //设置返回的字段 如果不设置返回选中的整个对象数组，如果设置了只返回设置的字段
      type: String,
      default: ""
    },
	  readOnly:{
        default:false
	  },
    value: null
  },
  data() {
    return {
      isDropdown: false, //是否展开树形选择器
      selectItems: [], //选中的选项
      dataval: this.value,
      showholder: true, //是否显示placeholder
      StrategyObj: {
        //数据返回模式指点
        SHOW_ALL: 1, //包括父级和子集
        SHOW_CHILD: 2 //只返回子集
      }
    };
  },
  directives: {
    clickoutside
  },
  computed: {
    //当前的数据返回模式
    curStrategyVal: function() {
      return this.StrategyObj[this.strategy];
    },
    //是否显示checkBox
    showCheckbox: function() {
      return this.multiple;
      // return this.multiple && this.curStrategyVal > 1;
    }
  },
  watch: {
    selectItems: {
      handler: function(curVal, oldVal) {
        //console.log("selectItems change");
        let self = this;
        if (curVal.length > 0) {
          self.showholder = false;
        } else {
          self.showholder = true;
        }
      },
      deep: true
    },
    value: {
      handler: function(curVal, oldVal) {

        if (curVal != oldVal) {
          console.log("value change");
          this.executPushToSelectItems();
        }
      }
    },
    treeData: {
      handler: function(curVal, oldVal) {
        if (curVal != oldVal) {
         // console.log("treeData change");
          this.executPushToSelectItems();

        }
      }
    }
  },
  created() {

  },
  mounted() {},

  methods: {
    getItemInTreeData(isSelect, items, attr, value) {
      let self = this;
      let ret = null;

      for (let i = 0; i < items.length; i++) {
        let item = items[i];
        if (item[attr] == value) {//这里不能用三等号
          if (this.showCheckbox) {
            if (!item.children) {
              item.checked = isSelect;
            }
          } else {
            item.selected = isSelect;
          }

          ret = JSON.parse(JSON.stringify(item));
          //delete ret.children;
          break;
        }
        if (item.children) {
          ret = self.getItemInTreeData(isSelect, item.children, attr, value);
          if (ret) break;
        }
      }
      return ret;
    },

    //清除tree中的选中状态
    clearTreeDataStatic(items, isSelect, isCheck) {
      for (let i = 0; i < items.length; i++) {
        let item = items[i];
        if (isSelect) {
          item.selected = false;
        }
        if (isCheck) {
          item.checked = false;
        }
        if (item.children) {
          this.clearTreeDataStatic(item.children, isSelect, isCheck);
        }
      }
    },
    //填充SelectItems
    pushToSelectItems(item) {
      if (item) {
        var index = this.selectItems.findIndex(it => {
          return it.key == item.key;
        });
        if (index < 0) {
          this.selectItems.push(item);
        }
      }
    },

    executPushToSelectItems() {
      let self = this;
      if (this.value!=null && this.value!=undefined) {
        this.selectItems.splice(0, this.selectItems.length);
        if (typeof this.value == "object") {
          if (this.value instanceof Array) {
            //数组
            if (this.retAttr && this.retAttr != "") {
              this.value.map(function(item) {
                let it = self.getItemInTreeData(
                  true,
                  self.treeData,
                  self.retAttr,
                  item
                );
                self.pushToSelectItems(it);
              });
            } else {
              this.value.map(function(item) {
                self.pushToSelectItems(
                  self.getItemInTreeData(true, self.treeData, "key", item.key)
                );
              });
            }
          } else {
            //对象 retAttr 不存在或者为空时，返回结果为对象

            self.pushToSelectItems(
              self.getItemInTreeData(true, self.treeData, "key", self.value.key)
            );
          }
        } else {
          //字符串 或 数字
			self.pushToSelectItems(
            self.getItemInTreeData(
              true,
              self.treeData,
              self.retAttr,
              self.value
            )
          );
        }
      }
    },

    //显示dropdown
    setIsOpen(isDropdown) {
        if(!this.readOnly){
            this.isDropdown = isDropdown;
		}

    },

    //tree 选择改变时
    onSelectChange(item) {
      let self = this;
      if (!this.showCheckbox) {
        this.selectItems.splice(0, this.selectItems.length);
        item.forEach(function(i) {
          let ii = JSON.parse(JSON.stringify(i));
          delete ii.children;
          self.selectItems.push(ii);
        });
      } else {
        //this.clearTreeDataStatic(this.treeData, true, false);
      }
      this.$emit("on-select-change",item[0]);
      self.sendVal();
    },

    //tree checkbox选择改变时
    onCheckChange(items) {
     
      let self = this;
      //let cleckItems = this.$refs.reftree.getCheckedNodes();
      //alert(JSON.stringify(cleckItems));
      this.selectItems.splice(0, this.selectItems.length);
      //this.selectItems=items;
      items.forEach(function(i) {
        let ii = JSON.parse(JSON.stringify(i));
        delete ii.children;
        switch (self.curStrategyVal) {
          case 1://全部
          let _ids=ii.parentIds.split(',');
          _ids.push(ii.key);
          _ids.map(function(id){
             if(self.selectItems.findIndex(it=>it.key==id)<0){
              let treeItem = self.getItemInTreeData(false,self.treeData, "key",id);
              if(treeItem){
                delete treeItem.children;
                self.selectItems.push(treeItem);
              }
             }
          })
         
            
            break;
          case 2://只要子集
            if (!i.children) {
              self.selectItems.push(ii);
            }
            break;
        }
      });
      self.sendVal();
      this.$emit("on-check-change",items)
    },

    //移除某个选中值
    removeItem(item) {
      let self = this;
      var _removeItem = function(_item) {
        if (_item.children) {
          for (let i = _item.children.length - 1; i >= 0; i--) {
            _removeItem(_item.children[i]);
          }
        }
        for (let a = self.selectItems.length - 1; a >= 0; a--) {
          if (self.selectItems[a].key == _item.key) {
            self.selectItems.splice(a, 1);
            break;
          }
        }
      };
      this.clearTreeDataStatic(this.treeData, true, true);
      let treeItem = {};
      if (this.retAttr && this.retAttr != "") {
        treeItem = this.getItemInTreeData(
          false,
          this.treeData,
          this.retAttr,
          item[this.retAttr]
        );
      } else {
        treeItem = this.getItemInTreeData(
          false,
          this.treeData,
          "key",
          item.key
        );
      }
      if (treeItem) {
        _removeItem(treeItem);
      }
      self.sendVal();
    },
    //清楚所有选择
    clearAllSelect() {
      let self = this;
      this.selectItems.splice(0, this.selectItems.length);
      this.sendVal();

      setTimeout(function() {
        self.clearTreeDataStatic(self.treeData, true, true);
      }, 0);
    },

    sendVal() {
      var self = this;
      let ret = [];
      if (!self.retAttr || self.retAttr == "") {
        ret = JSON.parse(JSON.stringify(this.selectItems));

        ret.map(function(it) {
          delete it.children;
        });
      } else {
        this.selectItems.map(function(item) {
          ret.push(item[self.retAttr]);
        });
      }
      if (!this.multiple) {
        ret = ret[0];
      }

      this.$emit("updateVal", ret);
    }
  }
};
</script>

<style>
.selectree {
  display: inline-block;
  width: 100%;
  height: 32px;
  position: relative;
  vertical-align: middle;
}

.selectree .selectInput {
  border: 1px solid #dddee1;
  border-radius: 3px;
  padding: 2px 10px;
  padding-right: 20px;
  line-height: 20px;
  width: 100%;
  min-height: 32px;
  height: 100%;
  overflow: hidden;
  display: inline-block;
  /* max-width: 200px; */
  /* min-width: 200px; */
  position: relative;
}

.selectree .ivu-dropdown-rel {
  height: 32px;
}

.selectree .selectInput .tipclose {
  position: absolute;
  right: 2px;
  top: 50%;
  color: #ddd;
  width: 16px;
  height: 16px;
  margin-top: -8px;
  cursor: pointer;
  /* text-indent: 2px; */
  line-height: 16px;
  /* border-radius: 50%; */
  /* background: #ddd; */
}

.selectree .selectInput .item {
  font-size: 12px;
}

/* 多选 */

.selectInput.multiple .item {
  font-size: 12px;
  padding: 3px 8px;
  background: #eee;
  padding-right: 18px;
  margin-right: 5px;
  position: relative;
  white-space: nowrap;
}

.selectInput.multiple .item:after {
  content: "×";
  color: #999;
  font-size: 14px;
  line-height: 12px;
  position: absolute;
  right: 0;
  top: 50%;
  margin-top: -6px;
  width: 12px;
  height: 12px;
  cursor: pointer;
}

.selectree {
  position: relative;
}



.selectree .ivu-dropdown {
  position: relative;
}

.selectree .ivu-select-dropdown {
  min-width: 100%;
}

.selectree .tip {
  font-size: 12px;
  color: #aaa;
  line-height: 30px;
  padding-left: 10px;
  position: absolute;
  left: 0;
  top: 0;
}
</style>